package cn.com.lsy.product.lepao.controller;

import cn.com.lsy.product.lepao.common.Constant;
import cn.com.lsy.product.lepao.controller.base.BaseController;
import cn.com.lsy.product.lepao.model.entities.LpEquipmentLogsTbl;
import cn.com.lsy.product.lepao.model.entities.LpStoreDataTotalTbl;
import cn.com.lsy.product.lepao.model.entities.LpStoreTbl;
import cn.com.lsy.product.lepao.model.entities.LpUserInfoTbl;
import cn.com.lsy.product.lepao.model.mt.entities.IncomeDataChartsDto;
import cn.com.lsy.product.lepao.model.mt.entities.NewCardTotalDto;
import cn.com.lsy.product.lepao.model.mt.entities.TodayStoreIncomeDto;
import cn.com.lsy.product.lepao.request.ActionLibraryInfoParam;
import cn.com.lsy.product.lepao.request.IncomeDataChartsParam;
import cn.com.lsy.product.lepao.request.SearchTodayStoreIncomeParam;
import cn.com.lsy.product.lepao.response.*;
import cn.com.lsy.product.lepao.response.base.ApiResponseEnum;
import cn.com.lsy.product.lepao.response.base.BaseRet;
import cn.com.lsy.product.lepao.service.*;
import cn.com.lsy.product.lepao.util.CommonFunctionUtil;
import cn.com.lsy.product.lepao.util.DozerMapperUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(value = "主页数据统计接口", tags = "主页数据统计接口")
@RestController
@RequestMapping(value = "/lepao/console/doAuth/statistical")
public class HomePageController extends BaseController {

    private Logger log = Logger.getLogger(HomePageController.class);

    @Autowired
    IDataTotalService iDataTotalService;
    @Autowired
    IUserService iUserService;
    @Autowired
    IDeviceService iDeviceService;
    @Autowired
    IStoreService iStoreService;
    @Autowired
    IStatisticalService iStatisticalService;
    @Autowired
    IFinanceService iFinanceService;

    @RequestMapping(value = "/totalStatistical", method = RequestMethod.POST)
    @ApiOperation(notes = "总数统计", httpMethod = "POST", value = "总数统计")
    public BaseRet<TotalStatisticalRet> totalStatistical() {

        BaseRet<TotalStatisticalRet> ret = new BaseRet<TotalStatisticalRet>();

        try {

            TotalStatisticalRet totalStatisticalRet = new TotalStatisticalRet();

            //当天时间
            String currentDate = CommonFunctionUtil.getStringTime(Constant.formatType.date);
            String startTime = currentDate + " 00:00:00";
            String endTime = currentDate + " 23:59:59";

            //今日新增用户
            BigDecimal currentNewUser = iDataTotalService.selectNewRegisterTotal(startTime, endTime);
            //今日入场
            int currentActiveUser = iDataTotalService.selectUserEnterTotal(startTime, endTime);
            //今日收益
            BigDecimal currentIncome = iDataTotalService.selectIncome(startTime, endTime, null);
            String monthStart = CommonFunctionUtil.getStringTime(Constant.formatType.year);
            //本月收益
            BigDecimal monthIncome = iDataTotalService.selectIncome(monthStart + "-01 00:00:00", CommonFunctionUtil.getMonthLastDay() + " 23:59:59", null);
            //累计用户
            int userTotal = iUserService.selectByCount("", "", "", "", 0, "", 0, "");
            totalStatisticalRet.setCurrentActiveUser(currentActiveUser);
            totalStatisticalRet.setCurrentIncome(currentIncome);
            totalStatisticalRet.setCurrentNewUser(currentNewUser);
            totalStatisticalRet.setMonthIncome(monthIncome);
            totalStatisticalRet.setUserTotal(userTotal);

            ret.setData(totalStatisticalRet);
            ret.setMsg("查询成功");
            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/incomeDataCharts", method = RequestMethod.POST)
    @ApiOperation(notes = "收益统计图（近15天）", httpMethod = "POST", value = "收益统计图（近15天）")
    public BaseRet<List<IncomeDataChartsRet>> incomeDataCharts(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody IncomeDataChartsParam param, BindingResult result) {

        BaseRet<List<IncomeDataChartsRet>> ret = new BaseRet<List<IncomeDataChartsRet>>();

        try {

            String startTime = "";
            String endTime = "";

            if (StringUtils.isNotEmpty(param.getStartTime())) {
                startTime = param.getStartTime() + " 00:00:00";
            }

            if (StringUtils.isNotEmpty(param.getEndTime())) {
                endTime = param.getEndTime() + " 23:59:59";
            }

            List<IncomeDataChartsDto> list = new ArrayList<IncomeDataChartsDto>();

            if (param.getStoreId() > 0) {
                list = iStatisticalService.selectStoreIncome(15, param.getType(), param.getStoreId(), startTime, endTime);
            } else {

                int pageSize = 15;//查询条数

                if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
                    pageSize = CommonFunctionUtil.caculateTotalTime(endTime, startTime) + 1;
                }

                list = iStatisticalService.selectPlatformIncome(pageSize, param.getType(), startTime, endTime);
            }

            List<IncomeDataChartsRet> listRet = DozerMapperUtil.mapList(list, IncomeDataChartsRet.class);

            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setMsg("查询成功");
            ret.setData(listRet);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/entranceDataCharts", method = RequestMethod.POST)
    @ApiOperation(notes = "入场统计图（近15天）", httpMethod = "POST", value = "入场统计图（近15天）")
    public BaseRet<List<IncomeDataChartsRet>> enterDataCharts(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody ActionLibraryInfoParam param, BindingResult result) {

        BaseRet<List<IncomeDataChartsRet>> ret = new BaseRet<List<IncomeDataChartsRet>>();

        try {

            List<IncomeDataChartsDto> list = new ArrayList<IncomeDataChartsDto>();

            if (param.getId() > 0) {
                list = iStatisticalService.selectStoreEnter(15, param.getId());
            } else {

                String startTime = "";
                String endTime = "";

                if (StringUtils.isNotEmpty(param.getStartTime())) {
                    startTime = param.getStartTime() + " 00:00:00";
                }

                if (StringUtils.isNotEmpty(param.getEndTime())) {
                    endTime = param.getEndTime() + " 23:59:59";
                }

                int pageSize = 15;//查询条数

                if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
                    pageSize = CommonFunctionUtil.caculateTotalTime(endTime, startTime) + 1;
                }

                list = iStatisticalService.selectPlatformEnter(pageSize, startTime, endTime);
            }

            List<IncomeDataChartsRet> listRet = DozerMapperUtil.mapList(list, IncomeDataChartsRet.class);

            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setMsg("查询成功");
            ret.setData(listRet);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/storeNumberTotal", method = RequestMethod.POST)
    @ApiOperation(notes = "场馆在线人数统计", httpMethod = "POST", value = "场馆在线人数统计")
    public BaseRet<List<StoreNumberTotalRet>> storeNumberTotal() {

        BaseRet<List<StoreNumberTotalRet>> ret = new BaseRet<List<StoreNumberTotalRet>>();

        try {

            List<StoreNumberTotalRet> listRet = new ArrayList<StoreNumberTotalRet>();

            List<LpStoreTbl> list = iStatisticalService.selectStoreByNumber();

            if (list != null && list.size() > 0) {
                for (LpStoreTbl value : list) {
                    StoreNumberTotalRet storeNumberTotalRet = new StoreNumberTotalRet();
                    storeNumberTotalRet.setOnlineSum(value.getOnlineSum());
                    storeNumberTotalRet.setStoreName(value.getStoreName());
                    storeNumberTotalRet.setState(iStatisticalService.getStoreNumberState(value.getOnlineSum()));
                    listRet.add(storeNumberTotalRet);
                }
            }

            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setMsg("查询成功");
            ret.setData(listRet);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/newCardTotal", method = RequestMethod.POST)
    @ApiOperation(notes = "新增月卡次卡数量统计", httpMethod = "POST", value = "新增月卡次卡数量统计")
    public BaseRet<NewCardTotalRet> newCardTotal(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody ActionLibraryInfoParam param, BindingResult result) {

        BaseRet<NewCardTotalRet> ret = new BaseRet<NewCardTotalRet>();

        try {

            String currentDate = CommonFunctionUtil.getStringTime(Constant.formatType.date);
            String startTime = currentDate + " 00:00:00";
            String endTime = currentDate + " 23:59:59";

            NewCardTotalRet newCardTotalRet = new NewCardTotalRet();

            if (param.getId() > 0) {
                //月卡
                int monthCard = iStatisticalService.selectStoreMonthCardNum(startTime, endTime, "month", param.getId());
                //次卡
                int dayCard = iStatisticalService.selectStoreMonthCardNum(startTime, endTime, "day", param.getId());
                newCardTotalRet.setDayCard(dayCard);
                newCardTotalRet.setMonthCard(monthCard);
            } else {
                NewCardTotalDto info = iStatisticalService.selectPlatformMonthCardNum(startTime, endTime);
                newCardTotalRet.setDayCard(info.getDayCard());
                newCardTotalRet.setMonthCard(info.getMonthCard());
            }

            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setMsg("查询成功");
            ret.setData(newCardTotalRet);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/searchTodayStoreIncome", method = RequestMethod.POST)
    @ApiOperation(notes = "查询门店当日收益情况", httpMethod = "POST", value = "查询门店当日收益情况")
    public BaseRet<List<TodayStoreIncomeRet>> searchTodayStoreIncome(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody SearchTodayStoreIncomeParam param, BindingResult result) {

        BaseRet<List<TodayStoreIncomeRet>> ret = new BaseRet<List<TodayStoreIncomeRet>>();

        try {

            checkParam(result);

            List<TodayStoreIncomeDto> list = iFinanceService.selectTodayStoreIncome(param.getStartTime() + " 00:00:00", param.getEndTime() + " 23:59:59");

            List<TodayStoreIncomeRet> listRet = DozerMapperUtil.mapList(list, TodayStoreIncomeRet.class);

            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setMsg("查询成功");
            ret.setData(listRet);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    /**
     * 没有记录购卡门店的用户设置默认最近去过的门店
     */
    private void setNotStoreIdUser() {

        List<LpUserInfoTbl> list = iUserService.selectNotStoreId();

        if (list != null && list.size() > 0) {

            for (LpUserInfoTbl value : list) {

                //查询用户入场记录
                List<LpEquipmentLogsTbl> useLog = iDeviceService.selectEquipmentLogsByUser(value.getId());
                if (useLog != null && useLog.size() > 0) {

                    //最近入场的门店id
                    int storeId = useLog.get(0).getStoreId();
                    JSONObject ext = new JSONObject();
                    if (StringUtils.isNotEmpty(value.getExt())) {

                        ext = JSONObject.parseObject(value.getExt());
                        ext.put("reg_store", storeId);
                        ext.put("cart_store", storeId);

                    } else {
                        ext.put("reg_store", storeId);
                        ext.put("cart_store", storeId);
                    }

                    LpUserInfoTbl lpUserInfoTbl = new LpUserInfoTbl();
                    lpUserInfoTbl.setId(value.getId());
                    lpUserInfoTbl.setExt(ext.toJSONString());
                    iUserService.updateUserInfo(lpUserInfoTbl);

                }
            }
        }
    }


    /**
     * 更新门店月卡收入
     */
    private void setStoreMonthIncome() {

        try {

            //获取日期列表
            List<String> list = CommonFunctionUtil.getDays("2019-06-10", "2019-09-09", Constant.formatType.date);

            //获取门店列表
            List<LpStoreTbl> store = iStoreService.selectByPage(0, 100, "", null);

            for (LpStoreTbl value : store) {

                for (String date : list) {

                    Date time = CommonFunctionUtil.changeTimeDate(date, Constant.formatType.date);
                    //获取当天月卡收入
                    BigDecimal total = iDataTotalService.selectStoreMonthCardIncome(date + " 00:00:00", date + " 23:59:59", value.getId());
                    //月卡入场
                    BigDecimal enterNum = iDataTotalService.selectMonthCardEnterTotal(date + " 00:00:00", date + " 23:59:59", value.getId());

                    LpStoreDataTotalTbl lpStoreDataTotalTbl = new LpStoreDataTotalTbl();
                    lpStoreDataTotalTbl.setMonthcardIncome(total);
                    lpStoreDataTotalTbl.setMonthcardEnterTotal(enterNum);

                    iDataTotalService.updateStoreMonthCardIncome(time, value.getId(), lpStoreDataTotalTbl);
                }

            }

        } catch (Exception e) {

        }


    }
}
